//
//  LDUserAccount.swift
//  Weibo201655
//
//  Created by pro on 16/5/6.
//  Copyright © 2016年 LeeDan. All rights reserved.
//

import UIKit

class LDUserAccount: NSObject, NSCoding {

    var access_token: String?
    // access_token的生命周期，单位是秒数。
    // 在Swift中如果是基本数据类型定义为可选,在KVC会找不到这个key
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
   
    var uid: String?
    
    // 过期时间,用于比较是否过期
    var expiresDate: NSDate?
    
    //用户昵称
    var screen_name: String?
    //用户头像地址
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
        super.init()
        // 只有 super.init() 后,对象才创建完毕,对象创建完毕后才能调用对象的方法
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    //MARK: 类常量：沙盒路径 userAccount.plist
    static let documentPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/userAccount.plist"
    
    
    //存储到沙盒
    func saveUserAccount() {
        //print(LDUserAccount.documentPath)
        NSKeyedArchiver.archiveRootObject(self, toFile: LDUserAccount.documentPath)
    }
    
    //从沙河盒获取用户信息
    class func getUserAccount()->LDUserAccount? {
        let acc = NSKeyedUnarchiver.unarchiveObjectWithFile(LDUserAccount.documentPath) as? LDUserAccount
        if acc != nil && acc?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("账号没有过期")
            return acc
        }
        return nil
    }
    
    //NSCoding代理方法
    // 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey:  "avatar_large")
    }
    
    // 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
}
